package com.boc.ewr.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boc.ewr.business.entity.CaUncaAll;
import com.boc.ewr.business.entity.vo.CaUncaAllRespVo;
import com.boc.ewr.business.mapper.CaUncaAllMapper;
import com.boc.ewr.business.service.ICaUncaAllService;
import com.xkcoding.http.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.enums.FileTypeEnum;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.collection.CollectionUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 未对账数据汇总表
 * @Author: jeecg-boot
 * @Date:   2023-04-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class CaUncaAllServiceImpl extends ServiceImpl<CaUncaAllMapper, CaUncaAll> implements ICaUncaAllService {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    CaUncaAllMapper caUncaAllMapper;


    @Override
    public boolean createInfo() {
        //清空当前记录
        caUncaAllMapper.delete(null);

        //获取当前时间
        String start = DateUtils.getYear() + "-01-01";
        String end = DateUtils.getYear() + "-12-31";
        List<CaUncaAll> listA2 = caUncaAllMapper.creatA2TypeInfo(start, end);
        List<CaUncaAll> listA3 = caUncaAllMapper.creatA3Typenfo(start, end);
        List<CaUncaAll> listC = caUncaAllMapper.creatCTypeInfo(start, end);
        List<CaUncaAll> result = new ArrayList<>();
        result.addAll(listA2);
        result.addAll(listA3);
        result.addAll(listC);
        //去重，取最新的记录，按照时间排序递减，然后用set集合去除重复的
        result = result.stream()
                .sorted((e1, e2) -> Integer.compare(Integer.valueOf(e2.getCaMon()), Integer.valueOf(e1.getCaMon())))//排序
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(o -> o.getAccNo() ))), ArrayList::new));//去重，根据账号

        return saveBatch(result);
    }


    /**
     * 导出TXT
     *
     * @param request
     */
    @Override
    public void exportTxt(HttpServletRequest request, HttpServletResponse response, CaUncaAll object) throws IOException {
        // Step.1 组装查询条件
        QueryWrapper<CaUncaAll> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
        //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id",selectionList);
        }
        // Step.2 获取导出数据
        List<CaUncaAll> exportList = caUncaAllMapper.selectList(queryWrapper);
        List<CaUncaAllRespVo> resultList = new ArrayList<>();
        for(CaUncaAll caUncaAll : exportList){
            CaUncaAllRespVo vo = new CaUncaAllRespVo();
            BeanUtils.copyProperties(caUncaAll, vo);
            resultList.add(vo);
        }
        //Step.3 生成txt文档
        String path = uploadpath + File.separator + DateUtils.yyyyMMdd.get().format(new Date());
        String fileName = DateUtils.date2Str(new SimpleDateFormat("yyyyMMddHHmmssSSS")) +"-"+ RandomStringUtils.randomNumeric(5);
        String filePath = createTxtByInfo(resultList, path, fileName);
        //Step.4 下载
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            response.setContentType("application/csv;charset=GBK");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
            File file = FileUtils.getFile(filePath);
            inputStream = new BufferedInputStream(FileUtils.openInputStream(file));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            log.error("预览文件失败" + e.getMessage());
            response.setStatus(404);
        } finally {
            inputStream.close();
            outputStream.close();
        }
    }

    /**
     * 根据数据生成文件，并保存到本地
     * @param infoList
     * @param path
     * @param fileName
     * @return
     * @throws IOException
     */
    protected String createTxtByInfo(List<CaUncaAllRespVo> infoList, String path, String fileName) throws IOException {

        if(CollectionUtil.isEmpty(infoList)){
            //数据为空
            log.info("数据为空，无需生成文件！");
            return "";
        }
        String fullPath = path + File.separator + fileName + FileTypeEnum.txt.getType();
        log.info("文件路径：{}，准备生成！", fullPath);
        File file = null;
        try {
            CommonUtils.filterFileName(fullPath);
            file = FileUtils.getFile(fullPath);
            CommonUtils.filterFileName(path);
            File folder = FileUtils.getFile(path);
            if (!folder.exists() && !folder.isDirectory()) {
                // 如果不存在,创建文件夹
                folder.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            log.error("生成文件失败！" , e);
            return "";
        }
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            /*String str = "账号|对账年月|账单号|客户号|未对账原因|其他未对账原因|处理状态|风险排查联系人|联系方式|";
            writer.write(str+"\r\n");*/
            for(CaUncaAllRespVo vo : infoList){
                String str = "";
                Field[] fields = vo.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //设置允许通过反射访问私有变量
                    field.setAccessible(true);
                    //获取字段的值
                    String value = ObjectUtil.isEmpty(field.get(vo)) ? "" : field.get(vo).toString();
                    //获取字段属性名称
                    String name = field.getName();
                    //其他自定义操作
                    if("serialVersionUID".equals(name)){
                        continue;
                    }
                    str = str + value + "|";
                }
                log.info("txt文件插入内容：{}", str);
                writer.write(str+"\r\n");
            }
        } catch (Exception e) {
            log.error("生成文件失败！" , e);
        } finally {
            writer.flush();
            writer.close();
        }
        return fullPath;
    }

}
